﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using Interface.Api;

namespace Sina.Api
{
	public class Login : IApi
	{
		public ApiResults execute(ApiArgs Args)
		{
			HttpWebRequest request = null;
			HttpWebResponse response = null;

			if (Args.GetType() != typeof(LoginArgs))
			{
				throw new Exception("Login.execute(): Expecting arguments of type LoginArgs but got " + Args.GetType().ToString());
			}

			LoginArgs loginInfo = (LoginArgs)Args;

			// Checking parameters
			if (loginInfo.username.Length == 0 || loginInfo.password.Length == 0)
			{
				throw new Exception("Login.execute(): Username or password shouldn't be empty.");
			}

			// Sending request
			request = (HttpWebRequest)WebRequest.Create(URL.Login + "?" + URL.Source);
			request.ContentType = "application/x-www-form-urlencoded";			// TODO:
			request.Method = "GET";
			request.Headers.Add("Authorization", "Basic " + loginInfo.authorization);

			try
			{
				response = (HttpWebResponse)request.GetResponse();
			}
			catch (WebException ex)
			{
				response = (HttpWebResponse)ex.Response;
			}
			catch (Exception)
			{
			}

			LoginResults results = new LoginResults();
			if (response != null)
			{
				results.status = response.StatusCode;
				response.Close();
			}
			else
			{
				// TODO: Throw exception here.
				results.status = HttpStatusCode.RequestTimeout;
			}

			return results;
		}
	}
}
